package com.jiezhuo.controller.jss;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jiezhuo.entity.cmeduSchool.*;
import com.jiezhuo.entity.jssgl.JssStuGagzjl;
import com.jiezhuo.entity.jssgl.JssStuJbqk;
import com.jiezhuo.entity.vo.TeacherCountVo;
import com.jiezhuo.service.IJwXqNjXjService;
import com.jiezhuo.service.IJwXqStudentService;
import com.jiezhuo.service.cmeduSchool.ITStuJtcyService;
import com.jiezhuo.service.cmeduSchool.StuService;
import com.jiezhuo.service.cmeduSchool.XxdwService;
import com.jiezhuo.service.cmeduSchool.XxdwXqService;
import com.jiezhuo.service.jss.JssCommonService;
import com.jiezhuo.service.jss.JssStuGagzjlService;
import com.jiezhuo.service.jss.JssStuJbqkService;
import com.jiezhuo.service.jss.JssXtUserlistService;
import com.jiezhuo.service.jzg.TJzgService;
import com.jiezhuo.utils.ListUtils;
import com.jiezhuo.utils.R;
import com.jiezhuo.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务控制器
 *
 * @author kancy
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2024-06-13 08:48:15
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@Api(tags = "寄宿生-教师教育记录汇总")
@RequestMapping("/jssStuGagzjl")
@Transactional
public class JssStuGagzjlController {
    @Autowired
    JssStuGagzjlService jssStuGagzjlService;

    @Autowired
    IJwXqStudentService jwXqStudentService;

    @Autowired
    TJzgService tJzgService;

    @Autowired
    XxdwXqService xxdwXqService;

    @Autowired
    XxdwService xxdwService;

    @Autowired
    JssStuJbqkService jssStuJbqkService;

    @Autowired
    ITStuJtcyService itStuJtcyService;

    @Autowired
    JssCommonService jssCommonService;

    @Autowired
    JssXtUserlistService jssXtUserlistService;

    @Autowired
    private IJwXqNjXjService jwXqNjXjService;
    @Autowired
    StuService stuService;

    @ApiOperation("查询教师教育记录汇总打印load")
    @GetMapping("getTeacherCountEdit")
    public R getCurrentUserInfo(@RequestParam("xq") String xq, @RequestParam("ng") String nj, @RequestParam("teacherId") String teacherId) {
//        String xq = "2022-2023-1";
//        String nj = "14";
//        String teacherId = "00001422";

        QueryWrapper<JssStuGagzjl> JssStuGagzjlQueryWrapper = new QueryWrapper<>();
        JssStuGagzjlQueryWrapper.eq("CreateUserId", teacherId);
        JssStuGagzjlQueryWrapper.eq("XQ", xq);
        List<JssStuGagzjl> jssStuGagzjlList = jssStuGagzjlService.list(JssStuGagzjlQueryWrapper);

        List<Map<String, Object>> dm_jss_zdlb = jssCommonService.getDMAll("dm_jss_zdlb");

        for (JssStuGagzjl jssStuGagzjl : jssStuGagzjlList) {
            for (Map<String, Object> map : dm_jss_zdlb) {
                if (jssStuGagzjl.getBjlb().equals(map.get("DM").toString())) {
                    jssStuGagzjl.setBjlbStr(map.get("MC").toString());
                }
            }
        }

        Set<String> stuIdSet = jssStuGagzjlList.stream().map(JssStuGagzjl::getStuId).collect(Collectors.toSet());


        QueryWrapper<JwXqStudent> jwXqStudentQueryWrapper = new QueryWrapper<>();
        jwXqStudentQueryWrapper.eq("XQ", xq);
        jwXqStudentQueryWrapper.eq("NJ", nj);
        jwXqStudentQueryWrapper.in("STU_ID", stuIdSet);
        // 数据
        List<JwXqStudent> jwXqStudentList = jwXqStudentService.list(jwXqStudentQueryWrapper);
        // 数据层级处理
        for (JwXqStudent jwXqStudent : jwXqStudentList) {
            List<JssStuGagzjl> collect = jssStuGagzjlList.stream().filter(x -> x.getStuId().equals(jwXqStudent.getStuId())).collect(Collectors.toList());
            jwXqStudent.getJssStuGagzjlList().addAll(collect);
        }


        List<List<Map<String, Object>>> mapList = new ArrayList<>();

        // header
        for (String s : stuIdSet) {
            List<Map<String, Object>> zdJlEdit = jwXqStudentService.getZdJlEdit(xq, s);

            QueryWrapper<JssStuJbqk> queryWrapperJbqk = new QueryWrapper();
            queryWrapperJbqk.eq("STUID", s);

            List<JssStuJbqk> jssStuJbqks = jssStuJbqkService.list(queryWrapperJbqk);
            // 赋值 对象
            for (Map<String, Object> map : zdJlEdit) {
                for (JssStuJbqk jssStuJbqk : jssStuJbqks) {
                    if (map.get("STU_ID").toString().equals(jssStuJbqk.getStuid())) {
                        map.put("jssStuJbqk", jssStuJbqk);
                    }
                }
            }
            // 处理底部
            List<JwXqStudent> collect = jwXqStudentList.stream().filter(x -> x.getStuId().equals(s)).collect(Collectors.toList());

            zdJlEdit.get(0).put("jwXqStudentList", collect);

            QueryWrapper<TStuJtcy> tStuJtcyQueryWrapper = new QueryWrapper<>();
            tStuJtcyQueryWrapper.eq("stu_id", s);
            // 数据
            List<TStuJtcy> tStuJtcies = itStuJtcyService.list(tStuJtcyQueryWrapper);

            zdJlEdit.get(0).put("tStuJtcies", tStuJtcies);
            mapList.add(zdJlEdit);
        }
        return R.ok().data("data", mapList);
    }

    @ApiOperation("查询教师教育记录汇总")
    @GetMapping("getTeacherCoount")
    public R getTeacherCoount(TeacherCountVo teacherCountVoProp) {

        if (jssXtUserlistService.isRoleXiao()) {
            teacherCountVoProp.setXqdm(jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
//            xxdwXqQueryWrapper.eq("NEW_XQDM", jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
        }
//        @RequestParam("xq") String xq, @RequestParam("current") Integer current, @RequestParam("size") Integer size
//        String xq = "2022-2023-1";
        String xq = teacherCountVoProp.getSemester();
        QueryWrapper<JssStuGagzjl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("XQ", xq);

        List<JssStuGagzjl> gagzjlList = jssStuGagzjlService.list(queryWrapper);

        // 获取学生Id集合
        Set<String> stuIdSet = gagzjlList.stream().map(JssStuGagzjl::getStuId).collect(Collectors.toSet());
        // 获取老师集合
        Set<String> teacherSet = gagzjlList.stream().map(JssStuGagzjl::getCreateuserid).collect(Collectors.toSet());


        // 获取学生详细信息
        QueryWrapper<JwXqStudent> queryWrapperJwXq = new QueryWrapper<>();
        queryWrapperJwXq.eq("XQ", xq);
        queryWrapperJwXq.in("STU_ID", stuIdSet);
        List<JwXqStudent> studentListInfo = jwXqStudentService.list(queryWrapperJwXq);

        // 年级的集合
        Set<String> njSet = new HashSet<>();

        Map<String, String> stuIdAndNj = new HashMap<>();

        for (JwXqStudent jwXqStudent : studentListInfo) {
            njSet.add(jwXqStudent.getNj());
            stuIdAndNj.put(jwXqStudent.getStuId(), jwXqStudent.getNj());
        }
        // 赋值年级代码
        gagzjlList = gagzjlList.stream().map(x -> x.setNjDM(stuIdAndNj.get(x.getStuId()))).collect(Collectors.toList());

        List<TeacherCountVo> teacherCountVoList = new ArrayList<>();
        // 在这里统计
        for (String teacherId : teacherSet) {
            List<JssStuGagzjl> collect = gagzjlList.stream().filter(x -> teacherId.equals(x.getCreateuserid())).collect(Collectors.toList());
            for (String nj : njSet) {
                long count = collect.stream().filter(x -> x.getNjDM().equals(nj)).count();
                TeacherCountVo teacherCountVo = new TeacherCountVo();
                teacherCountVo.setTeacherId(teacherId);
                teacherCountVo.setNjDM(nj);
                teacherCountVo.setXQ(xq);
                teacherCountVo.setCount(count + "");
                teacherCountVoList.add(teacherCountVo);
            }
        }
        teacherCountVoList = teacherCountVoList.stream().filter(x -> !x.getCount().equalsIgnoreCase("0")).collect(Collectors.toList());
        // 统计到此结束
        // 获取老师的姓名
        Map<String, String> teacherIdAndName = new HashMap<>();

        QueryWrapper<TJzg> teacherQuery = new QueryWrapper<>();
        teacherQuery.in("TeacherId", teacherSet);
        List<TJzg> teacherList = tJzgService.list(teacherQuery);

        // 老师和校区
        Map<String, String> teacherIdAndXQDM = new HashMap<>();

        // 校区代码 集合
        Set<String> xqDMSet = new HashSet<>();

        for (TJzg tJzg : teacherList) {
            teacherIdAndName.put(tJzg.getTeacherid(), tJzg.getXm());
            teacherIdAndXQDM.put(tJzg.getTeacherid(), tJzg.getGzXqdm());
            xqDMSet.add(tJzg.getGzXqdm());
        }

        teacherCountVoList = teacherCountVoList.stream().peek(x -> x.setXM(teacherIdAndName.get(x.getTeacherId()))).collect(Collectors.toList());

        // 校区简称赋值
        QueryWrapper<XxdwXq> xxdwXqQuery = new QueryWrapper<>();
        xxdwXqQuery.in("NEW_XQDM", xqDMSet);
        List<XxdwXq> list = xxdwXqService.list(xxdwXqQuery);

        Map<String, String> xqdmAndJc = new HashMap<>();

        for (XxdwXq xxdwXq : list) {
            xqdmAndJc.put(xxdwXq.getNewXqdm(), xxdwXq.getXqjc());
        }

        teacherCountVoList = teacherCountVoList.stream().peek(x -> {
                    x.setXqjc(xqdmAndJc.get(teacherIdAndXQDM.get(x.getTeacherId())));
                    x.setXqdm(teacherIdAndXQDM.get(x.getTeacherId()));
                }
        ).collect(Collectors.toList());

        // 设置年级名称
        Map<String, String> dmnjMap = new HashMap<>();

        List<Map<String, Object>> dm_nj = xxdwService.getDistList("dm_nj");
        for (Map<String, Object> dmnj : dm_nj) {
            dmnjMap.put(String.valueOf(dmnj.get("DM")), String.valueOf(dmnj.get("MC")));
        }

        teacherCountVoList = teacherCountVoList.stream().peek(x -> x.setNjMc(dmnjMap.get(x.getNjDM()))).collect(Collectors.toList());

        Map<String, Object> mapR = new HashMap<>();
        if (teacherCountVoProp.getXqdm() != null && !"".equals(teacherCountVoProp.getXqdm())) {
            teacherCountVoList = teacherCountVoList.stream().filter(x -> x.getXqdm().equals(teacherCountVoProp.getXqdm())).collect(Collectors.toList());
        }

        if (teacherCountVoProp.getJzzXm() != null && !"".equals(teacherCountVoProp.getJzzXm())) {
            teacherCountVoList = teacherCountVoList.stream().filter(x -> x.getXM().contains(teacherCountVoProp.getJzzXm())).collect(Collectors.toList());
        }

        mapR.put("count", teacherCountVoList.size());
        if (teacherCountVoList.size() != 0) {
            teacherCountVoList = (List<TeacherCountVo>) ListUtils.subList(teacherCountVoList, teacherCountVoProp.getSize(), teacherCountVoProp.getCurrent());
        }
        mapR.put("data", teacherCountVoList);

        return R.ok().data("data", mapR);
    }

    @ApiOperation("教师教育记录汇总loadData学校")
    @GetMapping("getTeacherCountLoadDataIsXqDm")
    public R getTeacherCountLoadDataIsXqDm() {
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<XxdwXq> xxdwXqQuery = new QueryWrapper<>();
        xxdwXqQuery.eq("SFJSZGL", "1");
        xxdwXqQuery.eq("DQZT", "1");
        if (jssXtUserlistService.isRoleXiao()) {
            xxdwXqQuery.eq("NEW_XQDM", jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
        }
        List<XxdwXq> list = xxdwXqService.list(xxdwXqQuery);
        map.put("xq", list);
        return R.ok().data("data", map);
    }

    @ApiOperation("教师教育记录汇总loadData老师")
    @GetMapping("getTeacherCountLoadDataIsTeacher")
    public R getTeacherCountLoadDataIsTeacher(@RequestParam String xqdm) {
        List<JssStuGagzjl> list = jssStuGagzjlService.list();
        Set<String> collect = list.stream().map(JssStuGagzjl::getCreateuserid).collect(Collectors.toSet());

        QueryWrapper<TJzg> jzgQueryWrapper = new QueryWrapper<>();
        jzgQueryWrapper.eq("GZ_XQDM", xqdm);
        jzgQueryWrapper.in("TeacherId", collect);

        List<TJzg> tJzgList = tJzgService.list(jzgQueryWrapper);
        return R.ok().data("data", tJzgList);
    }


    @ApiOperation("教师教育记录汇总loadData学期")
    @GetMapping("getTeacherCountLoadDataIsXq")
    public R getTeacherCountLoadDataIsXq() {
        List<JssStuGagzjl> list = jssStuGagzjlService.list();
        Set<String> collect = list.stream().map(JssStuGagzjl::getXq).collect(Collectors.toSet());
        ArrayList<String> strings = new ArrayList<>(collect);
        Collections.reverse(strings);
        return R.ok().data("data", strings);
    }

    @ApiOperation("教育与指导工作记录 校区控件filter")
    @GetMapping("getJiaoYuZhidaoJilvFilterXqdm")
    public R getJiaoYuZhidaoJilvFilterXqdm() {
        // 下拉列表
        QueryWrapper<XxdwXq> xxdwXqQueryWrapper = new QueryWrapper();
        xxdwXqQueryWrapper.eq("NEW_XQDM", jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
        List<XxdwXq> xxdwXqList = xxdwXqService.list(xxdwXqQueryWrapper);

        return R.ok().data("data", xxdwXqList);
    }

    @ApiOperation("教育与指导工作记录 年级控件filter")
    @GetMapping("getJiaoYuZhidaoJilvFilterNj")
    public R getJiaoYuZhidaoJilvFilterNj() {
        // 下拉列表
        JwXqStudent jwXqStudent = new JwXqStudent();
        jwXqStudent.setXq(jwXqNjXjService.getMaxXQ());
        jwXqStudent.setNewXqdm(jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
        List<Map<String, Object>> jiaoYuZhidaoJilvFilterXqdmNj = jwXqStudentService.getJiaoYuZhidaoJilvFilterXqdmNj(jwXqStudent);
        return R.ok().data("data", jiaoYuZhidaoJilvFilterXqdmNj);
    }

    @ApiOperation("教育与指导工作记录 班级控件filter")
    @GetMapping("getJiaoYuZhidaoJilvFilterBj")
    public R getJiaoYuZhidaoJilvFilterBj(String nj) {
        // 下拉列表
        JwXqStudent jwXqStudent = new JwXqStudent();
        jwXqStudent.setNj(nj);
        jwXqStudent.setXq(jwXqNjXjService.getMaxXQ());
        jwXqStudent.setNewXqdm(jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
        List<Map<String, Object>> jiaoYuZhidaoJilvFilterXqdmNj = jwXqStudentService.getJiaoYuZhidaoJilvFilterXqdmBj(jwXqStudent);
        jiaoYuZhidaoJilvFilterXqdmNj = jiaoYuZhidaoJilvFilterXqdmNj.stream().filter(x -> !"".equals(x.get("BJNO"))).collect(Collectors.toList());

        return R.ok().data("data", jiaoYuZhidaoJilvFilterXqdmNj);
    }


    @ApiOperation("教育与指导工作记录 学生控件filter")
    @GetMapping("getJiaoYuZhidaoJilvFilterStu")
    public R getJiaoYuZhidaoJilvFilterStu(JwXqStudent jwXqStudent) {
        jwXqStudent.setXq(jwXqNjXjService.getMaxXQ());
        List<Map<String, Object>> jiaoYuZhidaoJilvFilterStu = jwXqStudentService.getJiaoYuZhidaoJilvFilterStu(jwXqStudent);
        return R.ok().data("data", jiaoYuZhidaoJilvFilterStu);
    }


    @ApiOperation("教育与指导工作记录")
    @GetMapping("getJiaoYuZhidaoJilv")
    public R getJiaoYuZhidaoJilv(JwXqStudent jwXqStudent) {
        jwXqStudent.setXq(jwXqNjXjService.getMaxXQ());

// 学生基本信息
        List<Map<String, Object>> jiaoYuZhidaoJilv = jwXqStudentService.getJiaoYuZhidaoJilv(jwXqStudent);

        // 指导基本信息
        List<Map<String, Object>> yuZhidaoJilv = jssStuGagzjlService.getJiaoYuZhidaoJilv(jwXqStudent);

        if (yuZhidaoJilv.size() == 0) {
            return R.ok().data("data", null);
        }
        // 获取老师idList
        Set<String> teacherIdList = yuZhidaoJilv.stream().map(x -> x.get("CreateUserId") != null ? x.get("CreateUserId").toString() : "").collect(Collectors.toSet());

        QueryWrapper<TJzg> tJzglistQueryWrapper = new QueryWrapper<>();
        tJzglistQueryWrapper.in("TeacherId", teacherIdList);
        // 老师信息
        List<TJzg> tJzgList = tJzgService.list(tJzglistQueryWrapper);
        Map<String, TJzg> mapJzg = ListUtils.convertMapToTJzg(tJzgList, "TeacherId");
        // 赋值老师姓名
        yuZhidaoJilv = yuZhidaoJilv.stream().peek(x -> {
            if (x.get("CreateUserId") != null) {
                x.put("teacherName", mapJzg.get(x.get("CreateUserId").toString()));
            }

        }).collect(Collectors.toList());
        jiaoYuZhidaoJilv.get(0).put("zhidao", yuZhidaoJilv);

        return R.ok().data("data", jiaoYuZhidaoJilv);
    }


    @ApiOperation("教育与指导工作记录 save load")
    @GetMapping("getJiaoYuZhidaoJilSaveLoad")
    public R getJiaoYuZhidaoJilSaveLoad(String gzlb) {
        Map<String, Object> map = new HashMap<>();
        // 下拉列表
        List<Map<String, Object>> mapList = jssCommonService.getDMAll("dm_jss_zdlb");

        List<Map<String, Object>> gzLbList = mapList.stream().filter(x -> x.get("LB") == null && "1".equals(x.get("ZT").toString())).collect(Collectors.toList());
        List<Map<String, Object>> gzlx = null;
        if (gzlb != null && !"".equals(gzlb)) {

            if ("01".equals(gzlb)) {
                gzlx = mapList.stream().filter(x -> "01".equals(x.get("LB")) && "1".equals(x.get("ZT").toString())).collect(Collectors.toList());
            }
            if ("02".equals(gzlb)) {
                gzlx = mapList.stream().filter(x -> "02".equals(x.get("LB")) && "1".equals(x.get("ZT").toString())).collect(Collectors.toList());
            }
        }
        map.put("gzLb", gzLbList);
        map.put("gzlx", gzlx);
        return R.ok().data("data", map);
    }


    @ApiOperation("教育与指导工作记录 save update ")
    @PostMapping("addJiaoYuZhidaoJilSaveOrUpdate")
    public R addJiaoYuZhidaoJilSaveOrUpdate(@RequestBody JssStuGagzjl jssStuGagzjl) {
        if (jssStuGagzjl.getGadate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(jssStuGagzjl.getGadate());
            int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 获取星期几，星期日为1，星期一为2，依此类推
            String[] daysOfWeek = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
            jssStuGagzjl.setDay(daysOfWeek[dayOfWeek - 1]);
        }
        if (StringUtils.isStringNotExist(jssStuGagzjl.getId())) {
            jssStuGagzjl.setId(UUID.randomUUID().toString());
            jssStuGagzjl.setXq(jwXqNjXjService.getMaxXQ());
            jssStuGagzjl.setCreatedate(new Date());
            jssStuGagzjl.setWarning("0");
            jssStuGagzjl.setCreateuserid(jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
            jssStuGagzjlService.save(jssStuGagzjl);
        } else {
            jssStuGagzjl.setXq(jwXqNjXjService.getMaxXQ());
            jssStuGagzjl.setModifydate(new Date());
            jssStuGagzjl.setWarning("0");
            jssStuGagzjl.setCreateuserid(jssXtUserlistService.getAdminUserOne().getJzg().getGzXqdm());
            UpdateWrapper<JssStuGagzjl> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("ID", jssStuGagzjl.getId());
            jssStuGagzjlService.update(jssStuGagzjl, updateWrapper);
        }

        Map<String, Object> map = new HashMap<>();


        return R.ok().data("data", "操作成功");
    }
}